<template>
  <transition-group name="hand-drawn-toast" tag="div" class="hand-drawn-toast-container">
    <div
      v-for="toast in toasts"
      :key="toast.id"
      class="hand-drawn-toast"
      :class="[`hand-drawn-toast--${toast.type}`, { 'hand-drawn-toast--dismissible': toast.dismissible }]"
      @click="toast.dismissible && dismiss(toast.id)"
    >
      <div class="toast-content" :ref="el => setToastContentRef(el, toast.id)">
        <svg 
          :ref="el => setSvgRef(el, toast.id)"
          class="hand-drawn-border"
          :width="toast.svgWidth || 300"
          :height="toast.svgHeight || 85"
        ></svg>
        
        <div class="toast-main" :data-toast-id="toast.id">
          <div class="toast-icon">
            <span v-if="toast.type === 'success'">✓</span>
            <span v-else-if="toast.type === 'error'">✗</span>
            <span v-else-if="toast.type === 'warning'">⚠</span>
            <span v-else-if="toast.type === 'info'">ⓘ</span>
            <span v-else>{{ toast.emoji || '📝' }}</span>
          </div>
          
          <div class="toast-text">
            <div v-if="toast.title" class="toast-title">{{ toast.title }}</div>
            <div class="toast-message">{{ toast.message }}</div>
          </div>
          
          <div v-if="toast.dismissible" class="toast-close" @click.stop="dismiss(toast.id)">
            ×
          </div>
        </div>
      </div>
    </div>
  </transition-group>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import rough from 'roughjs'

interface HandDrawnToast {
  id: string
  type: 'success' | 'error' | 'warning' | 'info' | 'custom'
  title?: string
  message: string
  duration?: number
  dismissible?: boolean
  emoji?: string
  svgWidth?: number
  svgHeight?: number
}

const toasts = ref<HandDrawnToast[]>([])

// 存储每个toast的DOM引用
const toastContentRefs = new Map<string, HTMLElement>()
const svgRefs = new Map<string, SVGSVGElement>()
const resizeObservers = new Map<string, ResizeObserver>()

// ref设置函数
const setToastContentRef = (el: any, id: string) => {
  if (el && el instanceof HTMLElement) {
    toastContentRefs.set(id, el)
  } else {
    toastContentRefs.delete(id)
  }
}

const setSvgRef = (el: any, id: string) => {
  if (el && el instanceof SVGSVGElement) {
    svgRefs.set(id, el)
    // 设置ref后立即初始化
    nextTick(() => {
      initializeToastBorder(id)
    })
  } else {
    svgRefs.delete(id)
  }
}

// 初始化toast边框
const initializeToastBorder = (id: string) => {
  const contentEl = toastContentRefs.get(id)
  const svgEl = svgRefs.get(id)
  const toast = toasts.value.find(t => t.id === id)
  
  if (contentEl && svgEl && toast) {
    updateToastSvgSize(id)
    drawHandDrawnBorder(id)
    
    // 设置ResizeObserver监听尺寸变化
    const resizeObserver = new ResizeObserver(() => {
      nextTick(() => {
        updateToastSvgSize(id)
        drawHandDrawnBorder(id)
      })
    })
    resizeObserver.observe(contentEl)
    resizeObservers.set(id, resizeObserver)
  }
}

// 更新SVG尺寸 - 与HandDrawnCard相同逻辑
const updateToastSvgSize = (id: string) => {
  const contentEl = toastContentRefs.get(id)
  const toast = toasts.value.find(t => t.id === id)
  
  if (!contentEl || !toast) return
  
  const borderOverflow = 0
  const width = contentEl.offsetWidth + borderOverflow * 2
  const height = contentEl.offsetHeight + borderOverflow * 2
  
  toast.svgWidth = width
  toast.svgHeight = height
}

// 动态绘制手绘边框 - 与HandDrawnCard完全一致
const drawHandDrawnBorder = (id: string) => {
  const svgEl = svgRefs.get(id)
  const toast = toasts.value.find(t => t.id === id)
  
  if (!svgEl || !toast) return
  
  svgEl.innerHTML = ''
  const svg = rough.svg(svgEl)
  const borderColor = getBorderColor(toast.type)
  
  // 与HandDrawnCard完全相同的绘制逻辑
  for (let i = 0; i < 2; i++) {
    const mainRect = svg.rectangle(
      0,
      0,
      toast.svgWidth || 300,
      toast.svgHeight || 85,
      {
        stroke: borderColor,
        strokeWidth: 0.5 + i * 0.3,
        roughness: 2.5,
        seed: Math.random() * 1000 + i,
        fill: 'none',
        curveStepCount: 8
      }
    )
    svgEl.appendChild(mainRect)
  }
}

const getBorderColor = (type: string) => {
  // 使用与HandDrawnCard相同的颜色映射
  const colors = {
    success: '#b6fcb6',  // chalk-green
    error: '#ffb7c5',    // chalk-pink (accent)
    warning: '#ffe066',  // chalk-yellow (primary)
    info: '#aee9f5',     // chalk-blue (secondary)
    custom: '#fff'       // chalk-white (default)
  }
  return colors[type as keyof typeof colors] || colors.custom
}

const show = (options: Omit<HandDrawnToast, 'id' | 'svgWidth' | 'svgHeight'>) => {
  const id = Math.random().toString(36).substr(2, 9)
  
  const toast: HandDrawnToast = {
    ...options,
    id,
    duration: options.duration ?? 4000,
    dismissible: options.dismissible ?? true,
    svgWidth: 300,
    svgHeight: options.title ? 85 : 65
  }
  
  toasts.value.push(toast)
  
  // 自动关闭
  if (toast.duration && toast.duration > 0) {
    setTimeout(() => {
      dismiss(id)
    }, toast.duration)
  }
  
  return id
}

const dismiss = (id: string) => {
  // 清理资源
  const resizeObserver = resizeObservers.get(id)
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObservers.delete(id)
  }
  
  toastContentRefs.delete(id)
  svgRefs.delete(id)
  
  const index = toasts.value.findIndex(t => t.id === id)
  if (index > -1) {
    toasts.value.splice(index, 1)
  }
}

const success = (message: string, title?: string, options?: Partial<HandDrawnToast>) => {
  return show({ type: 'success', message, title, ...options })
}

const error = (message: string, title?: string, options?: Partial<HandDrawnToast>) => {
  return show({ type: 'error', message, title, ...options })
}

const warning = (message: string, title?: string, options?: Partial<HandDrawnToast>) => {
  return show({ type: 'warning', message, title, ...options })
}

const info = (message: string, title?: string, options?: Partial<HandDrawnToast>) => {
  return show({ type: 'info', message, title, ...options })
}

const custom = (message: string, title?: string, emoji?: string, options?: Partial<HandDrawnToast>) => {
  return show({ type: 'custom', message, title, emoji, ...options })
}

const clear = () => {
  // 清理所有资源
  resizeObservers.forEach(observer => observer.disconnect())
  resizeObservers.clear()
  toastContentRefs.clear()
  svgRefs.clear()
  
  toasts.value = []
}

// 组件卸载时清理所有资源
onUnmounted(() => {
  clear()
})

// 导出方法供外部使用
defineExpose({
  show,
  success,
  error, 
  warning,
  info,
  custom,
  dismiss,
  clear
})
</script>

<style lang="scss" scoped>
.hand-drawn-toast-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 3000;
  pointer-events: none;
}

.hand-drawn-toast {
  position: relative;
  width: 300px;
  margin-bottom: 16px;
  pointer-events: auto;
  font-family: 'Comic Sans MS', 'Marker Felt', cursive;
  
  .toast-content {
    position: relative;
    background: #222d22;  // 使用chalk主题背景色
    border-radius: 8px;
    padding: 16px 20px;
    color: #fff;
    box-shadow: 3px 3px 0 #111a11;  // 使用chalk-shadow
  }
  
  .hand-drawn-border {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;
    overflow: visible;  // 确保SVG不被截取
  }
  
  .toast-main {
    position: relative;
    z-index: 2;
    display: flex;
    align-items: center;  // 改为center让所有元素垂直居中
    gap: 12px;
    min-height: 24px;  // 确保有最小高度
  }
  
  .toast-icon {
    font-size: 18px;
    font-weight: bold;
    flex-shrink: 0;
    margin-top: 1px;
    line-height: 1;
    width: 20px;
    text-align: center;
  }
  
  .toast-text {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  
  .toast-title {
    font-size: 15px;
    font-weight: bold;
    margin-bottom: 4px;
    line-height: 1.3;
    color: #fff;
  }
  
  .toast-message {
    font-size: 13px;
    line-height: 1.4;
    color: rgba(255, 255, 255, 0.9);
  }
  
  .toast-close {
    font-size: 18px;
    font-weight: bold;
    cursor: pointer;
    opacity: 0.7;
    transition: opacity 0.2s;
    flex-shrink: 0;
    line-height: 1;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    
    &:hover {
      opacity: 1;
      background: rgba(255, 255, 255, 0.1);
    }
  }
  
  // 不同类型的样式
  &--success {
    .toast-icon {
      color: #b6fcb6;
    }
  }
  
  &--error {
    .toast-icon {
      color: #ffb7c5;
    }
  }
  
  &--warning {
    .toast-icon {
      color: #ffe066;
    }
  }
  
  &--info {
    .toast-icon {
      color: #aee9f5;
    }
  }
  
  &--custom {
    .toast-icon {
      color: #fff;
    }
  }
  
  // 可点击样式
  &--dismissible {
    cursor: pointer;
    
    &:hover {
      transform: translateY(-2px);
      
      .toast-content {
        box-shadow: 3px 5px 0 #111a11;  // 加大阴影
        
        .hand-drawn-border {
          filter: brightness(1.1);
        }
      }
    }
    
    &:active {
      transform: translateY(0);
      
      .toast-content {
        box-shadow: 3px 3px 0 #111a11;
      }
    }
  }
}

// 过渡动画 - 快速响应的弹出效果
.hand-drawn-toast-enter-active {
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  animation: handDrawnToastFadeIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.hand-drawn-toast-leave-active {
  transition: all 0.25s ease-in;
}

.hand-drawn-toast-enter-from {
  transform: translateX(100%) scale(0.95);
  opacity: 0;
}

.hand-drawn-toast-leave-to {
  transform: translateX(100%) scale(0.95);
  opacity: 0;
}

@keyframes handDrawnToastFadeIn {
  0% {
    opacity: 0;
    transform: translateX(100%) scale(0.9);
  }
  60% {
    opacity: 0.8;
    transform: translateX(-5%) scale(1.02);
  }
  100% {
    opacity: 1;
    transform: translateX(0) scale(1);
  }
}

.hand-drawn-toast-move {
  transition: transform 0.25s ease;
}

// 移动端适配
@media (max-width: 768px) {
  .hand-drawn-toast-container {
    right: 12px;
    left: 12px;
    top: 12px;
  }
  
  .hand-drawn-toast {
    width: auto;
    
    .toast-content {
      padding: 12px 16px;
    }
    
    .toast-title {
      font-size: 14px;
    }
    
    .toast-message {
      font-size: 12px;
    }
    
    .toast-icon {
      font-size: 16px;
      width: 18px;
    }
  }
}
</style> 